package com.luotao.test.nio;

import java.util.concurrent.Semaphore;

/**
 * Created by IntelliJ IDEA.
 * User: luotao
 * Date: 12-6-9
 * Time: 10:13
 */
public class ProviderAndConsumer {
    public static Semaphore semaphore = new Semaphore(5);

    public static class Provider implements Runnable {
        @Override
        public void run() {

            while (true) {
                System.out.println("provider ");
                semaphore.release();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    public static class Consumer implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    semaphore.acquire();
                    System.out.println("semaphore.getQueueLength() = " + semaphore.getQueueLength());
                    System.out.println("thread : "+Thread.currentThread().getId()+" get set start Consumer");

                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }

        }
    }


    public static void init() {
        for (int i = 0; i < 10; i++) {
            Thread provider = new Thread(new Provider());
            Thread consumer = new Thread(new Consumer());

            provider.start();
            consumer.start();
        }
    }

    public static void main(String[] args) throws Exception {
        init();
    }
}
